﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.ContentManagement.Drivers;
using Contrib.Sms.Models;
using Orchard.Localization;
using Orchard.ContentManagement;

namespace Contrib.Sms.Drivers
{
    public class TwilioSettingsPartDriver : ContentPartDriver<TwilioSettingsPart>
    {
        private const string TemplateName = "Parts/TwilioSettings";
        public Localizer T { get; set; }

        public TwilioSettingsPartDriver() {
            T = NullLocalizer.Instance;
        }

        protected override string Prefix { get { return "TwilioSettings"; } }

        protected override DriverResult Editor(TwilioSettingsPart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_TwilioSettings_Edit",
                    () => shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: part, Prefix: Prefix))
                    .OnGroup("SMS");
        }

        protected override DriverResult Editor(TwilioSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            return ContentShape("Parts_TwilioSettings_Edit", () =>
            {
                var previousAuthToken = part.AuthToken;
                updater.TryUpdateModel(part, Prefix, null, null);

                // restore password if the input is empty, meaning it has not been reseted
                if (string.IsNullOrEmpty(part.AuthToken))
                {
                    part.AuthToken = previousAuthToken;
                }
                return shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: part, Prefix: Prefix);
            }).OnGroup("SMS");
        }
    }
}